import 'package:flutter/material.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../config/config.dart';
import '../../widget/mq_text.dart';
import '../../widget/mq_button.dart';
import '../../services/screen_adapter.dart';
import '../../services/user_service.dart';
import '../../services/sign_service.dart';
import '../../services/event_bus.dart';



class AddressAddPage extends StatefulWidget {
  AddressAddPage({Key key}) : super(key: key);

  @override
  _AddressAddPageState createState() => _AddressAddPageState();
}

class _AddressAddPageState extends State<AddressAddPage> {

  String _area = '';
  String _name = '';
  String _phone = '';
  String _address = '';

  /// 页面销毁的时候进行事件广播
  @override
  void dispose() {
    super.dispose();
    eventBus.fire(new AddressEvent('增加地址成功...'));
    eventBus.fire(new CheckOutEvent('增加地址成功...'));
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init();
    return Scaffold(
      appBar: AppBar(
        title: Text('增加收货地址')
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: ListView(
          children: <Widget>[
            SizedBox(height: 20),
            MqText(
              text: '收货人姓名',
              onChange: (value) {
                setState(() => _name = value);
              }
            ),
            SizedBox(height: 10),
            MqText(
              text: '收货人电话',
              onChange: (value) {
                setState(() => _phone = value);
              }
            ),
            SizedBox(height: 10),
            InkWell(
              child: Container(
                padding: EdgeInsets.only(left: 5),
                height: ScreenAdapter.height(68),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      width: 1,
                      color: Colors.black12
                    )
                  )
                ),
                child: Row(
                  children: <Widget>[
                    Icon(Icons.add_location),
                    
                    _area.length > 0 ? Text(_area, style: TextStyle(
                      color: Colors.black54
                    )) :
                    Text('省/市/区', style: TextStyle(
                      color: Colors.black54
                    ))

                  ]
                )
              ),
              onTap: () async{
                Result result = await CityPickers.showCityPicker(
                  context: context,
                  cancelWidget: Text('取消', style: TextStyle(
                    color: Colors.black54
                  )),
                  confirmWidget: Text('确定', style: TextStyle(
                    color: Colors.black54
                  ))
                );

                setState(() => _area = '${result.provinceName}/${result.cityName}/${result.areaName}');

              }
            ),
            SizedBox(height: 10),
            MqText(
              maxLines: 4,
              height: 200,
              text: '详细地址',
              onChange: (value) {
                setState(() => _address = value);
              }
            ),
            SizedBox(height: 40),
            MqButton(
              text: '增加',
              color: Colors.red,
              callback: () async{
                List userinfo = await UserService.getUserInfo();
                // print(userinfo);
                /// salt用户注册的时候服务器随机生成的私钥
                var tempJson = {
                  'uid': userinfo[0]['_id'],
                  'name': _name,
                  'phone': _phone,
                  'address': '$_area $_address',
                  'salt': userinfo[0]['salt']
                };

                var sign = SignService.getSign(tempJson);
                // print(sign);

                var api = '${Config.domain}api/addAddress';
                var result = await Dio().post(api, data:{
                  'uid': userinfo[0]['_id'],
                  'name': _name,
                  'phone': _phone,
                  'address': '$_area $_address',
                  'sign': sign
                });
                // print(result);

                if(result.data['success']) {
                  Navigator.pop(context);
                } else {
                  Fluttertoast.showToast(
                    msg: "${result.data['message']}",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.CENTER,
                    timeInSecForIosWeb: 1,
                    backgroundColor: Colors.grey[600],
                    textColor: Colors.white,
                    fontSize: 16.0
                  );
                }

              }
            )

          ]
        )
      )
    );
  }
}